<template>
  <div v-loading="loading">
    <div class="coupon-card">
      <el-row :gutter="10">
        <el-col
          :xs="12"
          :sm="8"
          :md="8"
          v-for="(item, index) in cardData_1"
          :key="index"
        >
          <div class="app-main-content-box">
            <OnePointCard :data="item" />
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="form">
      <el-form
        :inline="true"
        :model="formData"
        class="demo-form-inline"
        label-width="80px"
        ref="formData"
        :rules="rules"
      >
        <el-row>
          <el-col :span="showMore ? 8 : 7">
            <el-form-item label="核销时间" size="small" prop="date">
              <el-date-picker
                v-model="formData.date"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
                type="datetimerange"
                range-separator="~"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="showMore ? 8 : 6">
            <el-form-item label="核销业务" size="small" prop="bizCode">
              <el-select
                v-model="formData.bizCode"
                filterable
                placeholder="请选择"
                style="width: 400px"
              >
                <el-option label="全部" value="" />
                <el-option
                  v-for="(item, index) in manageBizCodeOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.key"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="showMore ? 8 : 6">
            <el-form-item label="订单编号" size="small" prop="orderNo">
              <el-input
                v-model="formData.orderNo"
                placeholder="订单编号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5" v-if="!showMore">
            <el-button type="primary" round size="small" @click="search()"
              >查询</el-button
            >
            <el-button type="" round size="small" @click="resetForm('formData')"
              >重置</el-button
            >
            <el-button type="" round size="small" @click="exprotExcel()"
              >导出</el-button
            >
            <el-button type="text" size="small" @click="showMore = true"
              >展开</el-button
            >
          </el-col>
        </el-row>
        <div v-show="showMore">
          <el-row>
            <!-- <el-col :span="8">
              <el-form-item label="核销终端" size="small" prop="endpoint">
                <el-input
                  v-model="formData.endpoint"
                  placeholder="核销终端"
                ></el-input>
              </el-form-item>
            </el-col> -->
            <el-col :span="8">
              <el-form-item label="核销门店" size="small" prop="shopName">
                <el-input
                  v-model="formData.shopName"
                  placeholder="核销门店名称"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="核销方" size="small" prop="merchant">
                <el-cascader
                  v-model="formData.merchant"
                  :options="
                    [{ id: '', name: '全部' }].concat(allAuthMchOptions)
                  "
                  :props="{
                    checkStrictly: true,
                    value: 'id',
                    label: 'name',
                    children: 'shops',
                  }"
                  style="width: 100%"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="核销来源" size="small" prop="sourceCode">
                <el-select
                  v-model="formData.sourceCode"
                  filterable
                  placeholder="请选择"
                  style="width: 400px"
                >
                  <el-option label="全部" value="" />
                  <el-option
                    v-for="(item, index) in sourceCodeOptions"
                    :key="index"
                    :label="item.label"
                    :value="item.key"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="流水号" size="small" prop="serialNo">
                <el-input
                  v-model="formData.serialNo"
                  placeholder="交易流水号"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="券类型" size="small" prop="couponType">
                <el-select
                  v-model="formData.couponType"
                  filterable
                  placeholder="请选择"
                  style="width: 400px"
                >
                  <el-option label="全部" value="" />
                  <el-option label="折扣券" value="discount" />
                  <el-option label="兑换券" value="exchange" />
                  <el-option label="代金券" value="cash" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="券名称" size="small" prop="couponName">
                <el-input
                  v-model="formData.couponName"
                  placeholder="券名称"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="券码" size="small" prop="couponCode">
                <el-input
                  v-model="formData.couponCode"
                  placeholder="券码"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="!isDetail">
              <el-form-item label="顾客号码" size="small" prop="customerPhone">
                <el-input
                  v-model="formData.customerPhone"
                  placeholder="顾客号码"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="!isDetail">
              <el-form-item label="顾客" size="small" prop="customerName">
                <el-input
                  v-model="formData.customerName"
                  placeholder="顾客昵称/姓名"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="核销号码" size="small" prop="operatorPhone">
                <el-input
                  v-model="formData.operatorPhone"
                  placeholder="核销人员手机号"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="核销人员" size="small" prop="operatorName">
                <el-input
                  v-model="formData.operatorName"
                  placeholder="核销人员昵称/姓名"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-button type="primary" round size="small" @click="search()"
                >查询</el-button
              >
              <el-button
                type=""
                round
                size="small"
                @click="resetForm('formData')"
                >重置</el-button
              >
              <el-button type="" round size="small" @click="exprotExcel()"
                >导出</el-button
              >
              <el-button type="text" size="small" @click="showMore = false"
                >收起</el-button
              >
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>
    <div class="table-container app-main-content-box">
      <el-table
        :data="list"
        size="small"
        stripe
        border
        style="width: 100%"
        empty-text="暂无数据"
      >
        <el-table-column prop="createTime" label="核销时间" width="135" />
        <el-table-column prop="couponName" label="券名称" />
        <el-table-column prop="couponCode" label="券码" width="160">
          <template slot-scope="scope">
            {{ scope.row.couponCode }}
          </template>
        </el-table-column>
        <el-table-column prop="serialNo" label="流水号" width="160">
          <template slot-scope="scope">
            {{ scope.row.serialNo || "--" }}
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="订单编号" width="160">
          <template slot-scope="scope">
            <div
              v-if="scope.row.orderNo"
              @click="toOrderDetai(scope.row)"
              class="to-detail"
            >
              {{ scope.row.orderNo }}
            </div>
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="核销金额（元）">
          <template slot-scope="scope">
            <span>{{ (scope.row.verifyAmount / 100).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="couponType" label="类型">
          <template slot-scope="scope">
            <span>{{ couponTypeTableOptions[scope.row.couponType] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="核销来源">
          <template slot-scope="scope">
            <span>{{
              sourceCodeKeyOptions[scope.row.sourceCode] || "--"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="shopName" label="核销门店" width="150" />
        <!-- <el-table-column prop="endpoint" label="核销终端">
          <template slot-scope="scope">
            <span>{{ scope.row.endpoint || "--" }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="核销业务">
          <template slot-scope="scope">
            <span>{{ bizCodeKeyOptions[scope.row.bizCode] || "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="customerName"
          label="顾客"
          fixed="right"
          width="140"
        >
          <template slot-scope="scope">
            {{
              scope.row.customerPhone
                ? `${scope.row.customerName}(${scope.row.customerPhone})`
                : `${scope.row.customerName || "--"}`
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="operator"
          label="核销人员"
          fixed="right"
          width="180"
        >
          <template slot-scope="scope">
            {{
              scope.row.operatorPhone
                ? `${scope.row.operatorName}(${scope.row.operatorPhone})`
                : `${scope.row.operatorName || "--"}`
            }}
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination-direction
        v-if="paginationConfig.total !== 0"
        :config="paginationConfig"
        @sizeschange="sizesChange"
        @pagechange="pageChange"
      ></pagination-direction>
    </div>
  </div>
</template>

<script>
import {
  getCouponVerify,
  getCouponVerifyCount,
  exportCouponWriteOff,
} from "@/api/coupon";
import { mapGetters } from "vuex";
import OnePointCard from "./OnePointCard";
import { authMerchants } from "@/views/cardsAndOffer/api/mch";

export default {
  components: {
    OnePointCard,
  },
  props: {
    isDetail: {
      type: Boolean,
      default: false,
    },
    vipDetail: {
      type: Object,
    },
  },
  computed: {
    ...mapGetters([
      "manageShopList",
      "manageBizCodeOptions",
      "bizCodeKeyOptions",
      "sourceCodeOptions",
      "sourceCodeKeyOptions",
      "userInfo",
    ]),
  },
  data() {
    const validatorDate = (rule, value, callback) => {
      if (value && value.length) {
        callback();
      } else {
        callback(new Error("请选择时间"));
      }
    };
    return {
      activeTab: 1,
      rules: {
        date: [
          {
            validator: validatorDate,
            trigger: ["blur", "change"],
          },
        ],
      },
      // 配置
      paginationConfig: {
        // 分页配置
        direction: "center", // 分页位置
        layout: "total, sizes, prev, pager, next, jumper", // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 10,
        page: 1, // 页数-默认1
        pageSize: 10, // 每页条数-默认10
      },
      couponTypeTableOptions: {
        GENERAL: "通用券",
        CASH: "代金券",
        DISCOUNT: "折扣券",
        cash: "代金券",
        discount: "折扣券",
        exchange: "兑换券",
        cash_wx_busi: "微信商家代金券",
        discount_wx_busi: "微信商家折扣券",
        cash_wx_pay: "微信支付代金券",
      },
      // 表单数据
      formData: {
        date: [
          this.$momentMini().subtract(6, "days").format("YYYY-MM-DD") +
            " 00:00:00",
          this.$momentMini().format("YYYY-MM-DD") + " 23:59:59",
        ],
        bizCode: "",
        orderNo: "",
        // endpoint: "",
        shopName: "",
        merchant: "",
        sourceCode: "",
        couponType: "",
        couponName: "",
        customerPhone: "",
        customerName: "",
        operatorPhone: "",
        operatorName: "",
        serialNo: "",
        couponCode: "",
      },
      // 状态
      loading: false,
      // 头部卡片
      cardData_1: [],
      // 表格数据
      list: [],
      // 是否展示更多筛选想
      showMore: false,
      // 核销方筛选框数据
      allAuthMchOptions: [],
    };
  },
  async mounted() {
    await this.getAuthMerchants();
    await this.fetchData();
  },
  methods: {
    /**
     *  获取数据
     */
    // 获取数据
    fetchData(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      let { isDetail, formData } = this;
      let { merchant } = formData;
      this.$refs.formData.validate(async (valid) => {
        if (valid) {
          const params = Object.assign({}, formData);
          isDetail ? (params.customerId = this.vipDetail?.customer?.id) : "";
          params.start = formData.date[0];
          params.end = formData.date[1];
          if (merchant.length > 1) {
            params.merchant = merchant[0];
            params.shopId = merchant[1];
          } else if (merchant.length == 1) {
            params.merchant = merchant[0];
          }
          delete params.date;
          getCouponVerifyCount(params).then((res) => {
            if (res.code == 0) {
              this.cardData_1 = [["券/笔", res.data || 0]];
            }
          });
          params.pageSize = pageSize;
          params.page = page;
          getCouponVerify(params).then((res) => {
            if (res.code == 0) {
              this.list = res.data.list;
              this.paginationConfig.total = res.data.total;
              this.paginationConfig.page = res.data.pageNum;
            }
          });
        }
      });
    },

    // 分页sizes改变
    sizesChange() {
      this.fetchData();
    },
    // 分页page改变
    pageChange() {
      this.fetchData();
    },
    // 获取核销方下拉框数据
    getAuthMerchants() {
      let { id } = this.userInfo.business;
      return new Promise((resolve) => {
        authMerchants({ belongMerchant: id, queryType: 0 })
          .then((res) => {
            this.allAuthMchOptions = res.data;
          })
          .finally(() => {
            resolve();
          });
      });
    },
    search() {
      this.paginationConfig.page = 1;
      this.fetchData();
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.paginationConfig.page = 1;
      this.paginationConfig.pageSize = 10;
      this.fetchData();
    },
    exprotExcel(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      let { isDetail, formData } = this;
      let { merchant, date } = formData;
      const params = Object.assign({}, formData);
      isDetail ? (params.customerId = this.vipDetail?.customer?.id) : "";
      params.start = date ? formData.date[0] : "";
      params.end = date ? formData.date[1] : "";
      if (merchant.length > 1) {
        params.merchant = merchant[0];
        params.shopId = merchant[1];
      } else if (merchant.length == 1) {
        params.merchant = merchant[0];
      }
      delete params.date;
      params.pageSize = pageSize;
      params.page = page;
      exportCouponWriteOff(params).then((res) => {
        this.$alert("数据导出中，请稍后到数据下载中心进行下载", "提示", {
          confirmButtonText: "确定",
          center: true,
          type: "success",
          callback: (action) => {},
        });
      });
    },
    // 跳转各个详情弹窗
    toOrderDetai(row) {
      let { bizCode, orderNo } = row;
      let routeData;
      // 1 商城订单 2 预定订单 3 积分兑换订单 4 点餐订单 其他 预约订单
      // 9013 商城订单 9004 预定订单 9011积分商城  9005 点餐订单 9014 预约订单  9012码牌支付  9056 优惠券核销 9070 扫码领取优惠券
      let pathPar = {
        9013: "/wxaMallModule/orderManage",
        9004: "/bookingModule/orderRecord",
        9011: "/statement/points-mall-record",
        9005: "/wcyModule/orderRecord",
        9014: "/wxaReservationModule/orderManage",
      };
      let path = pathPar[bizCode];
      if (!path) {
        routeData = this.$router.resolve({
          path: "/payCenterDir/IncomeHis",
          query: { orderNo, from: "cancelTable" },
        });
      } else {
        routeData = this.$router.resolve({
          path,
          query: { orderNo, from: "cancelTable" },
        });
      }
      window.open(routeData.href, "_blank");
    },
  },
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.coupon-card {
  .app-main-content-box {
    margin-bottom: 10px;
  }
}
.form {
  background-color: #fff;
  padding: 20px 30px 0;
  /deep/.el-select,
  .el-date-editor--datetimerange {
    width: 100% !important;
  }
  .el-form-item {
    width: calc(100% - 20px) !important;
    display: flex;
    /deep/.el-form-item__content {
      flex: 1;
    }
  }
}
.to-detail {
  cursor: pointer;
  color: #f0b73d;
}
</style>
